<template>
	<view class="flex" style="align-items: center; gap: 20rpx;">
		<com-download v-if="fileInfo.url" :url="fileInfo.url" :title="title"></com-download>
		<button class="cu-btn cuIcon-upload line-blue radius" @click="uploadClick" v-if="!fileInfo.fileName">{{title}}</button>
		<button class="cu-btn cuIcon-upload line-blue radius" @click="uploadClick" v-else>重新上传</button>
	</view>
</template>

<script>
	import config from '../config'
	export default {
		props: {
			title: { type: String , default: "文件上传"},
			value: { type: String, default: ""}
		},
		data() {
			return {
				fileInfo: {
					fileName: "",
					url: ""
				}
			}
		},
		watch:{
			value(cur) {
				this.fileInfo.url = cur
				this.fileInfo.fileName = this.title
			}
		},
		methods: {
			uploadClick() {
				wx.chooseMessageFile({
					count: 1,
					type: "file",
					success:(res) => {
						const tempFilePaths = res.tempFiles
						console.log("tempFilePaths", tempFilePaths)
						if (tempFilePaths[0].size > 100 * 1024 * 1024) {
							uni.showToast({
								title: "文件大小不能超过100M",
								icon: "none"
							})
							return
						}
						uni.showLoading({
							title:"正在上传"
						})
						uni.uploadFile({
							url: 'https://test.jinpai.info/test-api/file/upload', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0].path,
							name: 'file',
							header: {
								"Authorization": uni.getStorageSync("token")
							},
							formData: {
								'user': 'test'
							},
							success: (uploadFileRes) => {
								this.fileInfo = JSON.parse(uploadFileRes.data).data
								console.log(this.fileInfo)
								this.fileInfo.fileName = tempFilePaths[0].name
								this.$emit("input", this.fileInfo.url)
							},
							fail:(res) => {
								console.log(res)
							},
							complete:() => {
								uni.hideLoading()
							}
						});
					}
				})
			}
		}
	}
</script>

<style lang="scss">
</style>